﻿using LL2024.Models.CommonLibraries.Interface;
using LL2024.Models.CommonLibraries.Services;
using System;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LL2024.Models.CommonLibraries
{
    public static class Common
    {
        private static IAESHelper _IAESHelper = new AESHelperService();
        private static NetTimeService _netTimeService = new NetTimeService();

        public static async Task<DateTime> GetNetDateTime()
        {
            return await _netTimeService.GetFastestInternetTime();
        }
        public static string ToEncrypt(this string str)
        {
            return _IAESHelper.ToEncrypt(str);
        }

        public static string ToDecrypt(this string str, string password)
        {

            return _IAESHelper.ToDecrypt(str, password);
        }

        /// <summary>
        /// 验证密码规则
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool ValidatePassword(string password)
        {
            var regex = new Regex(@"
(?=.*[0-9])                     #必须包含数字
(?=.*[a-z])                     #必须包含小写
(?=.*[A-Z])                     #必须包含大写
(?=([\x21-\x7e]+)[^a-zA-Z0-9])  #必须包含特殊符号
.{8,30}                         #至少8个字符，最多30个字符
", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);

            //如果要求必须包含小写、大写字母，则上面的(?=.*[a-zA-Z]) 要改为：
            /*
             * (?=.*[a-z])
             * (?=.*[A-Z])
             */
            return regex.IsMatch(password);
        }

        /// <summary>
        /// 检查网络是否可用
        /// </summary>
        /// <returns> 可用返回 <see langword="true"></see> 不可用返回 <see langword="false"></see></returns>
        public static bool IsNetworkAvailable()
        {
            try
            {
                // 进一步通过 Ping 验证网络连接
                using (var ping = new Ping())
                {
                    PingReply reply = ping.Send("8.8.8.8", 2000); // 尝试 Ping Google 的公共 DNS
                    return reply != null && reply.Status == IPStatus.Success;
                }
            }
            catch
            {
                // 发生异常视为无网络
                return false;
            }
        }
        public static async Task<bool> IsNetworkAvailableAsync()
        {
            return await Task.Run(() =>
            {
                return IsNetworkAvailable();
            });
        }



    }
}
